package com.neusoft.work.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.work.dao.BedAssignmentDao;
import com.neusoft.work.dao.BedInfoDao;
import com.neusoft.work.dao.CustomerDao;
import com.neusoft.work.dto.BedAssignmentDTO;
import com.neusoft.work.po.BedAssignment;
import com.neusoft.work.po.BedInfo;
import com.neusoft.work.po.Customer;
import com.neusoft.work.po.PageResponseBean;
import com.neusoft.work.po.ResponseBean;
import com.neusoft.work.service.BedAssignmentService;


@Service
public class BedAssignmentServiceImpl implements BedAssignmentService {
    @Autowired
    private BedAssignmentDao bad;

    @Autowired
    private CustomerDao cd;
    
    @Autowired
    private BedInfoDao bedInfoDao;

    @Override
    public ResponseBean<Integer> addBedAssignment(BedAssignment bs) {
        int count = bad.insert(bs);
        if (count > 0) {
            return new ResponseBean<>(bs.getId());
        } else {
            return new ResponseBean<>(500, "添加失败");
        }
    }

    @Override
    public ResponseBean<Integer> updateBedAssignment(BedAssignment bs) {
        int count = bad.updateById(bs);
        if (count > 0) {
            return new ResponseBean<>(bs.getId());
        } else {
            return new ResponseBean<>(500, "修改失败");
        }
    }

    @Override
    public ResponseBean<Integer> deleteBedAssignment(Integer id) {
        BedAssignment ba = new BedAssignment();
        ba.setId(id);
        ba.setIsDeleted(true);
        int count = bad.updateById(ba);
        if (count > 0) {
            return new ResponseBean<>(count);
        } else {
            return new ResponseBean<>(500, "删除失败");
        }
    }
    
    @Override
    public PageResponseBean<List<BedAssignmentDTO>> queryBedAssignmentInUse(
            String name,
            String assignStartTimeBegin,
            String assignStartTimeEnd,
            Boolean isDeleted,
            Long cur,
            Long number) {
        // 1. 查 customerId 列表
        List<Integer> custIds = null;
        if (name != null && !name.trim().isEmpty()) {
            custIds = cd.selectList(
                    new QueryWrapper<Customer>()
                        .like("name", name.trim())
                        .select("id")
            ).stream().map(Customer::getId).collect(Collectors.toList());
            if (custIds.isEmpty()) {
                return new PageResponseBean<>(500, "无数据");
            }
        }
        // 2. 分页与条件
        Page<BedAssignment> pageReq = new Page<>(cur, number);
        QueryWrapper<BedAssignment> qw = new QueryWrapper<>();
        if (custIds != null) qw.in("customerId", custIds);
        if (assignStartTimeBegin != null && !assignStartTimeBegin.isEmpty()) qw.ge("assignStartTime", assignStartTimeBegin);
        if (assignStartTimeEnd != null && !assignStartTimeEnd.isEmpty()) qw.le("assignStartTime", assignStartTimeEnd);
        if (isDeleted != null) qw.eq("isDeleted", isDeleted);

        IPage<BedAssignment> page = bad.selectPage(pageReq, qw);
        List<BedAssignment> list = page.getRecords();
        long total = page.getTotal();

        // 3. 批量加载客户信息
        List<Integer> customerIds = list.stream()
                .map(BedAssignment::getCustomerId)
                .distinct()
                .collect(Collectors.toList());
        if (customerIds.isEmpty()) {
            return new PageResponseBean<>(500,"无数据");
        }
        List<Customer> customers = cd.selectBatchIds(customerIds);
        var custMap = customers.stream()
                .collect(Collectors.toMap(Customer::getId, c -> c));

        // 4. 映射到 DTO
        List<BedAssignmentDTO> dtos = list.stream().map(r -> {
            Customer c = custMap.get(r.getCustomerId());
            BedAssignmentDTO dto = new BedAssignmentDTO();
            dto.setId(r.getId());
            dto.setCustomerId(r.getCustomerId());
            dto.setCustomerName(c == null ? null : c.getName());
            dto.setCustomerSex(c == null ? null : c.getGender());
            dto.setAssignStartTime(r.getAssignStartTime());
            dto.setAssignEndTime(r.getAssignEndTime());
            dto.setBedNumber(r.getBedNumber());
            dto.setIsDeleted(r.getIsDeleted());
            return dto;
        }).collect(Collectors.toList());

        // 5. 返回
        PageResponseBean<List<BedAssignmentDTO>> rb = new PageResponseBean<>(dtos);
        rb.setTotal(total);
        return rb;
    }

    
    @Override
    public ResponseBean<Integer> deleteByCustomer(Integer customerId) {
        BedAssignment assign = bad.selectOne(new QueryWrapper<BedAssignment>()
                .eq("customerId", customerId)
                .eq("isDeleted", false)
                .last("LIMIT 1")
        );
        if (assign == null) {
            return new ResponseBean<>(500, "无有效床位分配记录");
        }
        assign.setIsDeleted(true);
        int count = bad.updateById(assign);
        return count > 0
            ? new ResponseBean<>(count)
            : new ResponseBean<>(500, "删除失败");
    }

    @Override
    public ResponseBean<Integer> updateEndTimeByCustomer(Integer customerId, String assignEndTime) {
        BedAssignment assign = bad.selectOne(new QueryWrapper<BedAssignment>()
                .eq("customerId", customerId)
                .eq("isDeleted", false)
                .last("LIMIT 1")
        );
        if (assign == null) {
            return new ResponseBean<>(500, "无有效床位分配记录");
        }
        assign.setAssignEndTime(assignEndTime);
        int count = bad.updateById(assign);
        return count > 0
            ? new ResponseBean<>(count)
            : new ResponseBean<>(500, "更新结束时间失败");
    }

	@Override
    public ResponseBean<String> swapBed(Integer customerId, String newBedNumber) {
        try {
            // 1. 获取客户当前有效床位分配记录
            BedAssignment currentAssignment = bad.selectOne(
                new QueryWrapper<BedAssignment>()
                    .eq("customerId", customerId)
                    .eq("isDeleted", false)
            );
            
            if (currentAssignment == null) {
                return new ResponseBean<>(500, "该客户没有有效的床位分配记录");
            }
            
            // 2. 检查新床位是否空闲
            BedInfo newBed = bedInfoDao.selectOne(
                new QueryWrapper<BedInfo>().eq("bedNumber", newBedNumber)
            );
            
            if (newBed == null) {
                return new ResponseBean<>(500, "新床位不存在");
            }
            if (newBed.getStatus() != 1) { // 1表示空闲
                return new ResponseBean<>(500, "新床位不是空闲状态");
            }
            
            // 3. 获取当前日期
            String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            
            // 4. 更新原床位分配记录（结束时间为今天）
            currentAssignment.setAssignEndTime(today);
            currentAssignment.setIsDeleted(true);
            bad.updateById(currentAssignment);
            
            // 5. 创建新的床位分配记录
            BedAssignment newAssignment = new BedAssignment();
            newAssignment.setCustomerId(customerId);
            newAssignment.setBedNumber(newBedNumber);
            newAssignment.setAssignStartTime(today);
            newAssignment.setIsDeleted(false);
            bad.insert(newAssignment);
            
            // 6. 更新原床位状态为空闲
            BedInfo oldBed = bedInfoDao.selectOne(
                new QueryWrapper<BedInfo>().eq("bedNumber", currentAssignment.getBedNumber())
            );
            if (oldBed != null) {
                oldBed.setStatus(1); // 1表示空闲
                bedInfoDao.updateById(oldBed);
            }
            
            // 7. 更新新床位状态为占用
            newBed.setStatus(2); // 2表示占用
            bedInfoDao.updateById(newBed);
            
            // 8. 更新客户信息
            Customer customer = cd.selectById(customerId);
            if (customer != null) {
                customer.setBuilding("606");
                customer.setRoomNumber(newBed.getRoomNumber());
                customer.setBedNumber(newBedNumber);
                cd.updateById(customer);
            }
            
            return new ResponseBean<>("床位调换成功");
        } catch (Exception e) {
            return new ResponseBean<>(500, "床位调换失败: " + e.getMessage());
        }
    }
}
